package com.demo.controller;

import com.demo.common.AppResult;
import com.demo.common.AppConfig;
import com.demo.common.ResultCode;
import com.demo.exception.ApplicationException;
import com.demo.model.User;
import com.demo.services.IUserService;
import com.demo.utils.MD5Utils;
import com.demo.utils.StringUtils;
import com.demo.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.PublicKey;
import java.security.SecureRandom;

/**
 * @Author quan
 * @Description 6-Controller实现方法并对外提供API接口
 * @Date 2023/8/10 11:37
 */
@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    //注意：注入的是接口，不是实现类UserServiceImpl
    @Resource
    private IUserService userService;

    /**
     * 用户注册
     * @param username
     * @param nickname
     * @param password
     * @param passwordRepeat
     * @return
     */
    @ApiOperation("用户注册")
    @ResponseBody
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //1、正常写法：对传入的参数进行非空校验，如下：
        //但是这种写法比较麻烦。解锁新写法，在上面每个参数后面加@Nonnull就好了
//        if(StringUtils.isEmpty(username)
//        || StringUtils.isEmpty(nickname)
//        || StringUtils.isEmpty(password)
//        || StringUtils.isEmpty(enterPassword)){
//            //打印日志
//            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
//            //抛出异常
//            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
//        }

        //校验两次密码是否一致
        if(!passwordRepeat.equals(password)){
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 2、构建对象
        User user = new User();
        user.setUsername(username); //设置用户名
        user.setNickname(nickname); //设置昵称
        //对密码进行加盐（工具类）
        //(1)生成盐
        String salt = UUIDUtils.UUID_32();
        //(2)进行MD5加密
        String encryptPassword = MD5Utils.md5Salt(password,salt);
        //(3)设置密码和盐
        user.setSalt(salt); //设置盐
        user.setPassword(encryptPassword); //设置密码
        //3、调用service
        userService.createNormalUser(user);
        //4、返回结果
        return AppResult.success("注册成功！");
    }


    /**
     * 用户登录
     * @param request 请求
     * @param username 用户名
     * @param password 密码
     * @return AppResult
     */
    @ApiOperation("用户登录")
    @ResponseBody
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password){
        //1、非空校验
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2、调用接口：登录接口
        User user = userService.login(username,password);
        //3、设置session
        HttpSession session = request.getSession(true);//true没有的话就创建一个
        session.setAttribute(AppConfig.USER_SESSION_INFO,user);
        //3、返回数据
        return AppResult.success(user);
    }

    /**
     * 注销功能
     * @param request http请求
     * @return AppResult
     */
    @ApiOperation("退出登录")
    @ResponseBody
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        //1、获取session，设置为false，表示如果没有就不创建
        HttpSession session = request.getSession(false);
        //2、判断session是否为空，如果不为空就直接注销
        if(session!=null){
            log.debug("注销成功："+session.toString());
            //注销session
            session.invalidate();
        }
        //3、返回结果
        return AppResult.success("注销成功");
    }

    /**
     * 获取登录用户信息
     * @param request
     * @return AppResult<User>
     */
    @ApiOperation("获取用户信息")
    @ResponseBody
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户id") @RequestParam(value = "id",required = false) Long id){
        //1、定义返回的对象
        User user;
        //2、根据是否传入id进行处理：如果没有传入id，就获取登录用户信息；如果传入了id，就获取通过Id查询出来的对应的用户信息
        if(id == null){
            //(1)说明是登录用户:直接从session中获取登录用户信息
            //获取session
            HttpSession session = request.getSession(false);
            //获取用户
            user = (User)session.getAttribute(AppConfig.USER_SESSION_INFO);
        }else{
            //(2)调用service从id查询用户的接口中获取对应的用户信息
            user = userService.selectById(id);
        }
        //3、返回结果
        return AppResult.success(user);
    }

    /**
     * 修改个人信息
     * @param username 用户名(用于登录)
     * @param nickname 昵称
     * @param gender 性别
     * @param email 邮箱
     * @param phoneNumber 电话
     * @param remark 个人简介
     * @return AppResult<User>
     */
    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult<User> modifyInfo (HttpServletRequest request,
                                       @ApiParam("用户名(用于登录)") @RequestParam(value = "username", required = false) String username,
                                       @ApiParam("昵称") @RequestParam(value = "nickname", required = false) String nickname,
                                       @ApiParam("性别") @RequestParam(value = "gender", required = false) Byte gender,
                                       @ApiParam("邮箱") @RequestParam(value = "email", required = false) String email,
                                       @ApiParam("电话") @RequestParam(value = "phoneNumber", required = false) String phoneNumber,
                                       @ApiParam("个人简介") @RequestParam(value = "remark", required = false) String remark) {
        // 校验参数不能全部为空
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(nickname)
                && StringUtils.isEmpty(email) && StringUtils.isEmpty(phoneNumber)
                && StringUtils.isEmpty(remark) && gender == null) {
            // 返回提示
            return AppResult.failed("要修改的信息不能为空");
        }
        // 获取用户Id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_INFO);

        // 构造User对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户Id
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setPhoneNumber(phoneNumber); // 电话
        updateUser.setEmail(email); // 邮箱
        updateUser.setRemark(remark); // 个人简介

        // 调用Service
        userService.modifyInfo(updateUser);
        // 查询修改后的用户数据
        user = userService.selectById(user.getId());
        // 把User对象设置回session
        session.setAttribute(AppConfig.USER_SESSION_INFO, user);
        // 返回更新后的User对象
        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){

        //1-校验新密码和确认密码是否相同
        if(!newPassword.equals(passwordRepeat)){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //2-获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_INFO);
        //3-调用service
        userService.modifyPassword(user.getId(),oldPassword,newPassword);
        //4-销毁session
        if(session!=null){
            session.invalidate();
        }
        //5-返回结果
        return AppResult.success();
    }
}
